package com.jt.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.entity.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created by Administrator on 2017/4/8.
 */
@Component
public class JsonTemplate {

    private Logger logger = LoggerFactory.getLogger(JsonTemplate.class);

    private static ObjectMapper mapper = new ObjectMapper();

    static {
        /**
         * 正确处理“'”及不标准的 Key的 JSON
         */
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        /**
         * 忽略 null & ""
         */
        mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    }

    /**
     * 将 json字符串转为 java对象
     *
     * @param jsonStr
     * @param srcClass
     * @param <T>
     * @return
     */
    public <T> T jsonStr2Java(String jsonStr, Class<T> srcClass) {
        T target = null;
        try {
            target = mapper.readValue(jsonStr, srcClass);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return target;
    }


    /**
     * java 对象转为 json 字符串
     *
     * @param srcObj
     * @return
     */
    public String java2JsonStr(Object srcObj) {
        String target = "";
        try {
            target = mapper.writeValueAsString(srcObj);
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage(), e);
        }
        return target;
    }

}
